<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of controller
 *
 * @author phamhphuc
 */
class contest_action_controller extends contest_controller {   
    public $isEndOfContest = false;
    public function indexAction()
    {
        if(isset($_REQUEST['signed_request'])){
            $this->_forward("fbindex");
        } else {
            if($this->contest['show_signup_tab'] != "on" || ($this->isEndOfContest)) {
                $this->_forward("vote");
            } else {

                // this is data support for form builder submit form

                // get the form and build by form builder
                require_once '../libs/formbuilder.php';

                $formbuilder = null;

                if(!$this->_isCommented()) {

                    $formbuilder = new formbuilder();
                    $errorMsg = "";
                    if(isset($_POST['form'])) {
                        $user = $this->_getCurrentUser(false);
                        
                        $form = $_POST['form'];
                        
                        // start uploading file                      
                        $allowedExtensions = array('jpg','jpeg','png');
                        
                        // upload all of file to server first
                        foreach($_FILES as $k => $v) {
                            
                            //check extension
                            $info = pathinfo($_FILES[$k]["name"]);
                            
                            if(in_array($info['extension'], $allowedExtensions)){
                                $newfile = "uploads/" . time() . rand(1, 1000) . $_FILES[$k]["name"];
                                if(@move_uploaded_file($_FILES[$k]["tmp_name"], $newfile)) {
                                    $form[$k] = $newfile;
                                } else {
                                    $errorMsg = "Can't upload file, please check your file extension or size.";
                                }                                
                            } else {
                                $errorMsg = "We don't accept file type '{$info['extension']}'.";
                            }
                            
                        }

                        // to pass data through iframe you will need to encode all html tags
                        $form_data = json_encode($form);
                        
                        $data = array(
                            'form_data' => $form_data,
                            'smt_user_id' => $this->config['smt_user_id'],
                            'user_id' => $user['user_id'],
                            'contest_id' => $this->config['contest_id'],
                            'created_time' => date("Y-m-d H:i:s")
                        );
                        if($errorMsg != "") {
                            $formbuilder = new formbuilder($this->contest['form_fields']);
                            $formHTML = "";
                            if(trim($this->contest['form_fields']) != "") {
                                $formHTML = $formbuilder->getFormHTML();
                            }
                            $this->view->formHTML = $formHTML;
                            $this->view->errorMsg = $errorMsg;
                        } else {
                            $id = $this->db->insert("st_contest_data", $data);

                            if($id) {

                                $accessToken = $user['facebook_access_token'];
                                $facebook = $this->_getFacebookObject();

                                // get first text or text area content control
                                $firstText = "";
                                foreach($_POST['form'] as $k => $v) {
                                    $field = $formbuilder->parseFormFieldName($k);
                                    if($field['type'] == 'text' || $field['type'] == 'textarea') {
                                        $firstText = $v;
                                        break;
                                    }
                                }
                                if($firstText == "") {
                                    $firstText = $this->contest['autopost_title'];
                                }

                                // get friend list from post data
                                $friendString = "";
                                $friendNameList = "";
                                $friendIdList = "";
                                foreach($_POST['form'] as $k1 => $v1) {
                                    $field = $formbuilder->parseFormFieldName($k1);
                                    if($field['type'] == 'friendselector') {
                                        $d1 = (array) $v1;
                                        $friendNameList = $d1['name'];
                                        $friendIdList = $d1['ids'];
                                        $friendString = $this->parseFriendString($d1['name']);
                                        break;
                                    }
                                }

                                // post to current facebook user 's wall
                                $args = array(
                                    'message' => $this->contest['autopost_title'],
                                    'link' => $this->config['facebooktab_share_url'] . "&app_data=" . $id,
                                    'picture' => $this->contest['autopost_image'],
                                    'name' => $this->contest['autopost_title'],
                                    'description' => "{$this->contest['autopost_text']}
                                        {$friendString}
                                    "
                                );

                                $facebook->setAccessToken($accessToken);

                                if($this->contest['autopost_is_active'] == "on") {
                                    $facebook->api("/me/feed","post", $args);
                                }

                                // if we have friend selector then we will publish to that friendselector
                                if($friendString != "") {
                                    $friends = explode(", ", $friendIdList);

                                    $argsfriend = array(
                                        'message' => $firstText,
                                        'link' => $this->config['facebooktab_share_url'] . "&app_data=" . $id,
                                        'picture' => $this->contest['friendpost_image'],
                                        'name' => $this->contest['friendpost_title'],
                                        'description' => $this->contest['friendpost_text']
                                    );

                                    foreach($friends as $f) {
                                        if($f) {
                                            try {
                                                $facebook->api("/{$f}/feed","post", $argsfriend);
                                            } catch(FacebookApiException $e) {
                                                // get out of loop
                                                break;
                                            }
                                        }
                                    }
                                }
                            }

                            // get data for  form builder
                            header("location: ?action=index");die;
                            // end of get data for form builder
                        }
                        
                    } else {
                        $formbuilder = new formbuilder($this->contest['form_fields']);
                        $formHTML = "";
                        if(trim($this->contest['form_fields']) != "") {
                            $formHTML = $formbuilder->getFormHTML();
                        }
                        $this->view->formHTML = $formHTML;
                    }
                } else {
                    $formbuilder = new formbuilder();
                    $formHTML = "";
                    if(trim($this->view->commentData['form_data']) != "") {
                        $formHTML = $formbuilder->getFormHTMLFromData(json_decode($this->view->commentData['form_data']));
                    }
                    $this->view->formHTML = $formHTML;
                }

                // end of form builder support

                if(isset($_POST['data']) && (trim($_POST['data']['answer_text1']) != "") && (trim($_POST['data']['answer_text2']) != "")) {
                    if(!$this->_isCommented()) {
                        $user = $this->_getCurrentUser(false);
                        $data = $_POST['data'];
                        $data['smt_user_id'] = $this->config['smt_user_id'];
                        $data['user_id'] = $user['user_id'];

                        $data['contest_id'] = $this->config['contest_id'];

                        $data['created_time'] = date("Y-m-d H:i:s");

                        $tagfriends = $data['tagfriends'];
                        $tagfriends = "";
                        unset($data['tagfriends']);
                        $id = $this->db->insert("st_contest_data", $data);
                        if($id) {
                            $accessToken = $user['facebook_access_token'];
                            $facebook = $this->_getFacebookObject();

                            $friendString = $this->parseFriendString($data['answer_text2']);
                            /*
                            $args = array(
                                'message' => "Min venn fortjener dressen fordi: " . $data['answer_text1'],
                                'link' => $this->config['facebooktab_share_url'] . "&app_data=" . $id,
                                'picture' => "http://www.tierra.no/App_Themes/FrameworkBasic/images/custom/logo.png",
                                'name' => "Hjelp min venn å vinne en tierra-dress",
                                'description' => "Jeg deltar i Tierra.no sin konkurranse der min venn kan vinne en lekker Tierra-dress.
                                    {$friendString}
                                "
                            );
                            */
                            $args = array(
                                'message' => $this->contest['autopost_title'],
                                'link' => $this->config['facebooktab_share_url'] . "&app_data=" . $id,
                                'picture' => $this->contest['autopost_image'],
                                'name' => $this->contest['autopost_title'],
                                'description' => "{$this->contest['autopost_text']}
                                    {$friendString}
                                "
                            );

                            $facebook->setAccessToken($accessToken);

                            if($this->contest['autopost_is_active'] == "on") {
                                $facebook->api("/me/feed","post", $args);
                            }

                            if($data['answer_text3']) {
                                $friends = explode(", ", $data['answer_text3']);

                                $argsfriend = array(
                                    'message' => $this->contest['autopost_title'],
                                    'link' => $this->config['facebooktab_share_url'] . "&app_data=" . $id,
                                    'picture' => $this->contest['friendpost_image'],
                                    'name' => $this->contest['friendpost_title'],
                                    'description' => $this->contest['friendpost_text']
                                );

                                foreach($friends as $f) {
                                    if($f) {
                                        try {
                                            $facebook->api("/{$f}/feed","post", $argsfriend);
                                         } catch(FacebookApiException $e) {
                                             // get out of loop
                                             break;
                                         }
                                    }
                                }
                            }
                        }
                        $this->init();
                    }
                }
            }
        }
    }
    
    public function parseFriendString($string) {
        $str = str_replace(", ", ", @", $string);
        $str = "Jeg har invitert @{$str}";
        return $str;
    }
    
    public function tosAction(){
        $this->_setNoLayout();
    }
    public function fblikeviewAction()
    {
        $this->_setNoLayout();
        if(isset($_GET['data_id']) && (intval($_GET['data_id']) > 0)) {
            $this->view->data_id = intval($_GET['data_id']);            
        } else {
            $this->view->data_id = 0;
        }
    }
    
    public function gotofbAction()
    {
        header("location: {$this->config['facebooktab_share_url']}");die;
    }
    
    private function _getFacebookObject()
    {
        require_once '../libs/facebook/facebook.php';        
        $facebook = new Facebook(array(
          'appId'  => $this->config['facebook_app_id'],
          'secret' => $this->config['facebook_app_secret'],
          'fileUpload' => true
        ));
        return $facebook;
    }
    
    private function _isCommented()
    {
        $user = $this->_getCurrentUser();
        $sql = "select * from st_contest_data where user_id = '{$user['user_id']}' and contest_id = '{$this->config['contest_id']}'";
        $comment = $this->db->getRow($sql);
        if($comment){
            return true;
        } else {
            return false;
        }
    }
    
    private function _isEndOfContest()
    {
        if($this->contest['end_date'] == "" || $this->contest['end_date'] == 0) {
            return false;
        }
        
        $endTime = strtotime($this->contest['end_date']);
        $now = strtotime("now");
        if($now > $endTime) {
            return true;
        } else {
            return false;
        }
    }
    
    public function init()
    {        
        parent::init();
        if($this->_isLogined()) {                       
            $user = $this->_getCurrentUser(false);
            if(!$user) {
                $this->session->user = false;                
            } else {                
                $this->view->user = $user;
                $this->view->isLogined = true; 
                // check for is commented
                $sql = "select * from st_contest_data where user_id = '{$user['user_id']}' and contest_id = '{$this->config['contest_id']}'";
                $comment = $this->db->getRow($sql);
                if($comment){
                    $this->view->isCommented = true;
                    $this->view->commentData = $comment;
                } else {
                    $this->view->isCommented = false;
                }  
            }                      
        }
        $this->isEndOfContest = $this->_isEndOfContest();
        
        $this->view->isEndOfContest = $this->isEndOfContest;
        
        $this->view->isConnectedFacebook = $this->_isConnectedFacebook();        
    }
    
    private function _isConnectedFacebook()
    {
        if($this->_isLogined()) {
            $user = $this->_getCurrentUser();
            if($user['facebook_user_id'] != "") {
                return true;
            }
        }
        return false;
    }
    
    public function fbaboutAction()
    {
        $this->setlayout("facebooktab");
    }
    
    public function aboutAction()
    {
        
    }
    
    public function registerAction()
    {
        $error = "";
        
        if(isset($_POST['data'])){
            $data = $_POST['data'];
            if($data['password'] != $data['retype_password']) {
                $error = "Password does not match<br/>";
            } else {
                unset($data['retype_password']);
                $data['password'] = md5($data['password']);
            }
            
            $user = $this->db->getRow("select * from st_contest_user where email = {$data['email']}");
            if($user) {
                $error = "Email already exist<br/>";
            }
            
            if($error == "") {
                $data['smt_user_id'] = $this->config['smt_user_id'];
                $data['created_date'] = date("Y-m-d H:i:s");
                $this->db->insert("st_contest_user", $data);
                header("location: ?action=login");
            }
        }
    }
    
    public function loginAction()
    {       
        if($this->_isLogined()) {
            header("location: ?action=index");die;
        }
        if(isset($_POST['data'])){
            $data = $_POST['data'];
            $sql = "select * from st_contest_user where email = '{$data['email']}' and password = md5('{$data['password']}')";
            $user = $this->db->getRow($sql);
            if($user) {
                $this->session->user = $user;
                $this->db->update("st_contest_user", array(                    
                    "last_login" => date("Y-m-d H:i:s")
                ),"email = '{$user['email']}'");
                header("location: ?action=index");die;
            }
        }
    }
    
    public function loginfacebookAction()
    {
        $this->_setNoLayout();
        $userID = $_POST['userID'];
        $accessToken = $_POST['accessToken'];
        
        // get big profile picture
        $facebook = $this->_getFacebookObject();
        $facebook->setAccessToken($accessToken);
        
        $fbuser = $facebook->api('/me', array(
                          'fields' => 'picture, first_name, last_name, name, email, birthday, gender, hometown',
                          'type'   => 'large'
                      ));
        
        $hometown = "";
        
        if($fbuser['hometown']) {
            $hometown = $fbuser['hometown']['name'];
        }        
                
        $bigPicture     = $fbuser['picture'];

        $birthday = "";
        if($fbuser['birthday']) {
            $birthdays = explode("/", $fbuser['birthday']);
            $birthday = "{$birthdays[2]}-{$birthdays[0]}-{$birthdays[1]}";
        }
        
        // check if have user with this email
        $sql = "select * from st_contest_user where email = '{$fbuser['email']}' and contest_id = {$this->config['contest_id']}";                
//        echo $sql;die;
        $user = $this->db->getRow($sql);
        
//        print_r($fbuser);die;
//        print_r($user);die;
        
        if($user){      
            if($user['facebook_user_id'] == "") {
                $this->db->update("st_contest_user", array(
                   "facebook_user_id"  => $fbuser['id'],                                       
                   "facebook_user_picture" => $bigPicture,
                   "facebook_access_token" => $accessToken,
                   'birthday' => $birthday,
                   'gender' => $fbuser['gender'],
                    'hometown' => $hometown,
                   "last_login" => date("Y-m-d H:i:s")
                ),"email = '{$fbuser['email']}' and contest_id = {$this->config['contest_id']}");
            } else {
                $this->db->update("st_contest_user", array(
                    "facebook_access_token" => $accessToken,
                    "facebook_user_picture" => $bigPicture,   
                    'birthday' => $birthday,
                    'hometown' => $hometown,
                    "last_login" => date("Y-m-d H:i:s")
                ),"email = '{$fbuser['email']}' and contest_id = {$this->config['contest_id']}");
            }            
        } else {            
            $data = array(
                'first_name' => $fbuser['first_name'],
                'last_name' => $fbuser['last_name'],
                'name' => $fbuser['name'],
                'smt_user_id' => $this->config['smt_user_id'],
                'created_date' => date("Y-m-d H:i:s"),
                'email' => $fbuser['email'],
                'birthday' => $birthday,
                'gender' => $fbuser['gender'],
                'hometown' => $hometown,
                'facebook_user_data' => json_encode($fbuser),
                'facebook_user_picture' => $bigPicture,
                'facebook_access_token' => $accessToken,
                'facebook_user_id' => $fbuser['id'],
                'last_login' => date("Y-m-d H:i:s"),
                'contest_id' => $this->config['contest_id']
            );
            $this->db->insert("st_contest_user", $data);
            
            $sql = "select * from st_contest_user where email = '{$fbuser['email']}' and contest_id = {$this->config['contest_id']}";
            $user = $this->db->getRow($sql);     
        }        
        if($user) {            
            // login this user            
            $this->session->user = $user;
            echo json_encode(array(
                'status' => "1",
                'message' => "OK"
            ));
        }
    }
    
    private function _isLogined()
    {
        if($this->session->user) {
            return true;
        } else {
            return false;
        }
    }
    
    private function _getCurrentUser($useCache = true)
    {
        if(!$useCache) {
            $user = $this->session->user;
            $sql = "select * from st_contest_user where user_id = {$user['user_id']}";
            $this->session->user = $this->db->getRow($sql);
        }
        return $this->session->user;
        
    }
    
    public function voteAction()
    {
        if($this->config['facebookstatus']) {
            if(($this->contest['like_trap_is_active'] == "on") && ($this->config['facebookstatus']['page']['liked'] != "1")) {
                echo nl2br(str_replace("\\\"", "", $this->contest['like_trap_content']));die;
            }
        }
        
        if($this->contest['show_contribution_tab'] == "on") {
            $this->fbindexAction();            
        } else {
            $this->_forward("about");
        }  
        
//        $this->fbindexAction();
        $this->setlayout("default");
    }
    
    public function toplistAction()
    {
        
    }    
    
    public function logoutAction()
    {
        $this->session->user = false;
        header("location: ?action=index");
    }
    
    public function likeAction()
    {
        $this->_setNoLayout();
        $result = array();
        $result = array(
                    'status' => "0",
                    'message' => "Can't receive data"
                );
        if(isset($_POST['data_id'])) {
            
            $user = $this->_getCurrentUser();
            
            if($user) {                                   
                
                // check if current user liked
                $sqlSelect = "select * from st_contest_user_like_data where user_id = {$user['user_id']} and data_id = {$_POST['data_id']}";
                if(!$this->db->getRow($sqlSelect)) {
                    $data = array(
                        'data_id' => $_POST['data_id'],
                        'user_id' => $user['user_id'],
                        'smt_user_id' => $this->config['smt_user_id'],
                        'liked_time' => date("Y-m-d H:i:s")
                    );
                    $this->db->insert("st_contest_user_like_data", $data);
                    $this->_updateLikeNumberForData($_POST['data_id']);
                    
                    // get like data
                    $sqlLike = "select total_like from st_contest_data where data_id = {$_POST['data_id']}";
                    $dataLike = $this->db->getRow($sqlLike);
                    
                    $result = array(
                        'status' => "1",
                        'data_id' => $_POST['data_id'],
                        'numberoflike' => $dataLike['total_like'],
                        'message' => "Vote successfully!!!"
                    );
                    
                } else {
                    // get like data
                    $sqlLike = "select total_like from st_contest_data where data_id = {$_POST['data_id']}";
                    $dataLike = $this->db->getRow($sqlLike);
                    
                    $result = array(
                        'status' => "1",
                        'data_id' => $_POST['data_id'],
                        'numberoflike' => $dataLike['total_like'],
                        'message' => "You already liked"
                    );
                }
                
            } else {
                $result = array(
                    'status' => "0",
                    'message' => "Please login to vote"
                );
            }
        }
        echo json_encode($result);
    }
    
    public function unlikeAction()
    {
        $this->_setNoLayout();
        $result = array();
        $result = array(
                    'status' => "0",
                    'message' => "Can't unlike data"
                );
        if(isset($_POST['data_id'])) {
            
            $user = $this->_getCurrentUser();            
            if($user) {                
                $this->db->delete("st_contest_user_like_data", "user_id = {$user['user_id']} and data_id = {$_POST['data_id']}");                
                
                $this->_updateLikeNumberForData($_POST['data_id']);
                
                // get like data
                $sqlLike = "select total_like from st_contest_data where data_id = {$_POST['data_id']}";
                $dataLike = $this->db->getRow($sqlLike);
                
                $result = array(
                    'status' => "1",
                    'data_id' => $_POST['data_id'],
                    'numberoflike' => $dataLike['total_like'],
                    'message' => "Unlike successfully"
                );
                
            }
        }
        echo json_encode($result);
    }
    
    public function getnumberoflikeAction()
    {
        $this->_setNoLayout();
        $result = array();
        $result = array(
                    'status' => "0",                   
                    'message' => "Can't get data"
                );
        if(isset($_POST['data_id'])) {
            $sql = "select total_like from st_contest_data where data_id = {$_POST['data_id']}";
            $data = $this->db->getRow($sql);
//            echo $data['total_like'];die;
            $result = array(
                    'status' => "1",
                    'data_id' => $_POST['data_id'],
                    'numberoflike' => $data['total_like'],
                    'message' => "OK"
                );
        } else {
            $result = array(
                    'status' => "0",  
                    'data_id' => $_POST['data_id'],
                    'message' => "Can't get data"
                );            
        }
        echo json_encode($result);
    }
    
    public function youAction()
    {
        $dataID = @$_GET['data'];
        if(!$dataID) {
            header("location: ?action=index");die;
        } else {
            $dataID = intval($dataID);
        }
        
        $sql = "
        select * from 
            st_contest_user u 
            right join
            (
                select * from st_contest_data where data_id = {$dataID}
            ) c
            on u.user_id = c.user_id
        ";
                
        if($this->_isLogined()) {
            $user = $this->_getCurrentUser();
            $sql = "
                select * from 
                st_contest_user u 
                right join
                (
                        select d.*,l.user_like_id as is_liked 
                                from st_contest_data d 
                                left join 
                                (select * from st_contest_user_like_data where user_id = '{$user['user_id']}') l
                        on d.data_id = l.data_id	
                        where d.data_id = {$dataID}
                ) c
                on u.user_id = c.user_id
                ";
//                        echo $sql;die;
        }
        $this->view->comment = $this->db->getRow($sql);
    }
    
    private function _updateLikeNumberForData($dataID) {
        $getTotalSQL = "select count(*) as total_like from st_contest_user_like_data where data_id = {$dataID}";
        $data = $this->db->getRow($getTotalSQL);
        $updateSQL = "update st_contest_data set total_like = {$data['total_like']} where data_id = {$dataID}";
        $this->db->query($updateSQL);
    }
    
    private function _getPreDataID($id) {
        $sql = "select data_id from st_contest_data where contest_id = '{$this->config['contest_id']}' and data_id > {$id} order by data_id ASC";
        $data = $this->db->getRow($sql);
        if($data) {
            return $data['data_id'];
        } else {
            return 0;
        }
    }
    
    private function _getNextDataID($id) {
        $sql = "select data_id from st_contest_data where contest_id = '{$this->config['contest_id']}' and data_id < {$id} order by data_id DESC";
        $data = $this->db->getRow($sql);
        if($data) {
            return $data['data_id'];
        } else {
            return 0;
        }
    }
    
    // start UI on facebook tab
    public function fbindexAction(){
        
        if($this->config['facebookstatus']) {
            if(isset($this->config['facebookstatus']['app_data'])) {
                $this->view->app_data = intval($this->config['facebookstatus']['app_data']);
            }
        }
        
        $this->setlayout("facebooktab");
        
        // call vote action to get all of vote data
        $itemperpage = $this->config['facebooktab_item_per_page'];
        $orderBy = "";
        $limit = "";  
        $start = 0;        
        $currentPage = 1;
        
        if(isset($_GET['p'])) {
            $currentPage = intval($_GET['p']);
            if($currentPage <= 0) {
                $currentPage = 1;
            }
        }
        
        $start = ($currentPage - 1) * $itemperpage;
        $limit = $itemperpage;
        
        $limitString = " limit {$start}, {$limit}";
        
        if(isset($_GET['order'])) {
            $fieldName = mysql_escape_string($_GET['order']);
            $sort = "DESC";
            if(isset($_GET['sort']) && (strtolower($_GET['sort']) == "asc")){
                $sort = "ASC";
            }
            $orderBy = " order by {$fieldName} $sort";
        } else {
            $orderBy = "order by data_id DESC";
        }
        
        // get a list of comment
        $sql = "
        select * from 
            st_contest_user u 
            right join
            (
                select * from st_contest_data where contest_id = '{$this->config['contest_id']}'
            ) c
            on u.user_id = c.user_id
            {$orderBy}
            {$limitString}
        ";
        if($this->_isLogined()) {
            $user = $this->_getCurrentUser();
            $sql = "
                select * from 
                st_contest_user u 
                right join
                (
                        select d.*,l.user_like_id as is_liked 
                                from st_contest_data d 
                                left join 
                                (select * from st_contest_user_like_data where user_id = '{$user['user_id']}') l
                        on d.data_id = l.data_id	
                        where contest_id = '{$this->config['contest_id']}'
                ) c
                on u.user_id = c.user_id
                {$orderBy}
                {$limitString}
                ";
        }
        $comments = $this->db->getRows($sql);
        
        // split for 4 items per row
        $i= 0;
        $tmp = array();
        $newcomments = array();
        foreach($comments as $c) {
            $tmp[] = $c;
            $i++;
            if($i >= 4) {
                $i = 0;
                $newcomments[] = $tmp;
                $tmp = array();
            }
        }
        if(count($tmp) > 0) {
            $newcomments[] = $tmp;
        }
        
        // get total records
        $totalSql = "select count(*) as total from st_contest_data";
        $r = $this->db->getRow($totalSql);        
        $total = $r['total'];
        
        $numberOfPage = ceil($total/$itemperpage);
        
        $isFirst = false;
        if($currentPage == 1) {
            $isFirst = true;
        }
        
        $isLast = false;
        if($currentPage == $numberOfPage) {
            $isLast = true;
        }
        
        $pagination = array(
            'currentPage' => $currentPage,
            'total' => $total,
            'numberOfPage' => $numberOfPage,
            'isFirst' => $isFirst,
            'isLast' => $isLast
        );
        
//        echo "<pre>";print_r($pagination);die;
        $this->view->newcomments = $newcomments;
        $this->view->comments = $comments;   
        $this->view->pagination = $pagination;
    }
    
    public function fblikeboxAction()
    {
        $this->_setNoLayout();  
        
        $preID = 0;
        $nextID = 0;
        
        $dataID = @$_REQUEST['data_id'];
        if(!$dataID) {
            die("Can not get data ID");
        } else {
            $dataID = intval($dataID);
            $preID = $this->_getPreDataID($dataID);
            $nextID = $this->_getNextDataID($dataID);
        }
        // get a list of comment
        $sql = "
        select * from 
            st_contest_user u 
            right join
            (
                select * from st_contest_data where data_id = {$dataID}
            ) c
            on u.user_id = c.user_id
        ";
        if($this->_isLogined()) {
            $user = $this->_getCurrentUser();
            $sql = "
                select * from 
                st_contest_user u 
                right join
                (
                        select d.*,l.user_like_id as is_liked 
                                from st_contest_data d 
                                left join 
                                (select * from st_contest_user_like_data where user_id = '{$user['user_id']}') l
                        on d.data_id = l.data_id	
                        where d.data_id = {$dataID}
                ) c
                on u.user_id = c.user_id
                ";
        }                        
        
        $comment = $this->db->getRow($sql);
        
        
        // update anwer text 3 to answer text 2
        if($comment['answer_text3'] != "") {            
            $friendNames = explode(", ", $comment['answer_text2']);
            $friendIds = explode(", ", $comment['answer_text3']);
            foreach($friendNames as $k => &$v) {
                $v = "<a target='_blank' href='http://www.facebook.com/profile.php?id={$friendIds[$k]}'>$v</a>";
            }
//            print_r($friendNames);die;
            $comment['answer_text2'] = implode(", ", $friendNames);
        }
        
        $this->view->comment = $comment;
        
        $this->view->preID = $preID;
        $this->view->nextID = $nextID;
        
        // support for form builder
        require_once '../libs/formbuilder.php';
        $formHTML = "";
        $formbuilder = new formbuilder();
        if($comment['form_data'] != "") {
            $formHTML = $formbuilder->getFormHTMLLightboxFromData(json_decode($comment['form_data']));
        }
        $this->view->formHTML = $formHTML;
    }
    
    public function uploadAction()
    {
        require_once '../libs/uploader/server/php.php';
        
        // list of valid extensions, ex. array("jpeg", "xml", "bmp")
        $allowedExtensions = array('jpg','jpeg','png');
        
        // max file size in bytes
        $sizeLimit = 2 * 1024 * 1024;
        
        $uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
        $result = $uploader->handleUpload('uploads/');
        // to pass data through iframe you will need to encode all html tags
        echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);
        die;
    }
}

?>
